package ntd.remote.file.action;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import lj.a.tool.LJToolFile;
import ntd.action.ActionAbs;
import ntd.action.bo.ActionInBo;
import ntd.action.bo.ActionInfo;
import ntd.action.bo.ActionOutBo;
import ntd.remote.file.bo.ComRemoteFileBO;
import ntd.remote.link.ComRegistryServer;
import ntd.remote.link.bo.MsgBO;
import ntd.remote.online.ComOnline;
import ntd.remote.online.bo.OnlineInfo;
import ntd.util.fun.ComFun;

import java.io.File;
import java.util.List;

public class ActionRemoteDel extends ActionAbs {

    public static final String ACTION_CODE = "action-netty-remote-file-del";

    @Override
    public ActionInfo info() {
        return new ActionInfo("netty 远程文件删除操作", ACTION_CODE, this);
    }

    @Override
    public ActionOutBo handle() {
        MsgBO msgBOIn = actionInBo.getData().toBean(MsgBO.class);
        ComRemoteFileBO comRemoteFileBO = JSONUtil.toBean(msgBOIn.getData(), ComRemoteFileBO.class);

        StaticLog.info("LJ - netty 远程文件[{}]删除操作", comRemoteFileBO.getPath());

        DateTime dateTime = comRemoteFileBO.getDateTime();

        if (ObjectUtil.isNotNull(dateTime)) {
            LJToolFile.loopStreamFiles(comRemoteFileBO.getPath(), file -> {
                if (dateTime.getTime() > file.lastModified()) {
                    StaticLog.info("LJ - 删除文件[{}]", file.getPath());
                    FileUtil.del(file);
                }
            });

//            List<File> files = FileUtil.loopFiles(comRemoteFileBO.getPath());
//            // 过滤时间不合格的
//            for (File file : CollUtil.filter(files, file -> dateTime.getTime() > file.lastModified())) {
//            }
            // 删除空文件夹
            FileUtil.cleanEmpty(FileUtil.file(comRemoteFileBO.getPath()));
        } else {
            StaticLog.info("LJ - 删除文件[{}]", comRemoteFileBO.getPath());
            FileUtil.del(comRemoteFileBO.getPath());
        }

        return new ActionOutBo();
    }

    public static void main(String[] args) {
        ComRemoteFileBO comRemoteFileBO = new ComRemoteFileBO();
        comRemoteFileBO.setPath("D:\\work-file");
        comRemoteFileBO.setDateTime(DateUtil.parseDateTime("2023-06-14 00:00:00"));
        new ActionRemoteDel().execute(new ActionInBo().setDataStr(JSONUtil.toJsonStr(comRemoteFileBO)));
    }
}
